<?php
/**
 * 用户控制器
 * 处理用户注册、登录、健康信息管理等
 */

class UserController {
    private $db;
    
    public function __construct() {
        $database = Database::getInstance();
        $this->db = $database->getConnection();
    }
    
    /**
     * 用户登录
     */
    public function login($data) {
        try {
            validateParams($data, ['phone', 'password']);
            
            // 查询用户
            $stmt = $this->db->prepare("SELECT * FROM users WHERE phone = ? AND status = 1");
            $stmt->execute([$data['phone']]);
            $user = $stmt->fetch();
            
            if (!$user) {
                return apiError('用户不存在或已被禁用');
            }
            
            // 验证密码
            if (!password_verify($data['password'], $user['password'])) {
                return apiError('密码错误');
            }
            
            // 生成token
            $token = $this->generateToken($user['id']);
            
            // 更新最后登录时间
            $this->updateLastLogin($user['id']);
            
            return apiSuccess([
                'token' => $token,
                'userInfo' => [
                    'id' => $user['id'],
                    'nickName' => $user['nickname'],
                    'avatarUrl' => $user['avatar'],
                    'phone' => $user['phone']
                ]
            ], '登录成功');
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 用户注册
     */
    public function register($data) {
        try {
            validateParams($data, ['phone', 'password', 'code']);
            
            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $data['phone'])) {
                return apiError('手机号格式不正确');
            }
            
            // 验证密码长度
            if (strlen($data['password']) < 6) {
                return apiError('密码长度不能少于6位');
            }
            
            // 检查用户是否已存在
            $stmt = $this->db->prepare("SELECT id FROM users WHERE phone = ?");
            $stmt->execute([$data['phone']]);
            if ($stmt->fetch()) {
                return apiError('该手机号已注册');
            }
            
            // 验证短信验证码（这里简化处理，实际需要验证）
            if ($data['code'] !== '123456') { // 测试用验证码
                return apiError('验证码错误');
            }
            
            // 创建用户
            $nickname = '用户' . substr($data['phone'], -4);
            $passwordHash = password_hash($data['password'], PASSWORD_DEFAULT);
            
            $stmt = $this->db->prepare("INSERT INTO users (phone, password, nickname, avatar, created_at) VALUES (?, ?, ?, ?, NOW())");
            $stmt->execute([
                $data['phone'],
                $passwordHash,
                $nickname,
                '/images/default-avatar.png'
            ]);
            
            $userId = $this->db->lastInsertId();
            
            // 生成token
            $token = $this->generateToken($userId);
            
            return apiSuccess([
                'token' => $token,
                'userInfo' => [
                    'id' => $userId,
                    'nickName' => $nickname,
                    'avatarUrl' => '/images/default-avatar.png',
                    'phone' => $data['phone']
                ]
            ], '注册成功');
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 获取用户信息
     */
    public function getUserInfo($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            
            $stmt = $this->db->prepare("SELECT u.*, h.blood_sugar, h.uric_acid, h.bmi, h.weight, h.height FROM users u LEFT JOIN user_health h ON u.id = h.user_id WHERE u.id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();
            
            if (!$user) {
                return apiError('用户不存在');
            }
            
            $userInfo = [
                'id' => $user['id'],
                'nickName' => $user['nickname'],
                'avatarUrl' => $user['avatar'],
                'phone' => $user['phone'],
                'healthInfo' => [
                    'bloodSugar' => $user['blood_sugar'],
                    'uricAcid' => $user['uric_acid'],
                    'bmi' => $user['bmi'],
                    'weight' => $user['weight'],
                    'height' => $user['height']
                ]
            ];
            
            return apiSuccess($userInfo);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 更新健康信息
     */
    public function updateHealthInfo($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            validateParams($data, ['bloodSugar', 'uricAcid', 'weight', 'height']);
            
            // 计算BMI
            $bmi = $data['weight'] / (($data['height'] / 100) * ($data['height'] / 100));
            
            // 检查是否已有健康记录
            $stmt = $this->db->prepare("SELECT id FROM user_health WHERE user_id = ?");
            $stmt->execute([$userId]);
            
            if ($stmt->fetch()) {
                // 更新记录
                $stmt = $this->db->prepare("UPDATE user_health SET blood_sugar = ?, uric_acid = ?, bmi = ?, weight = ?, height = ?, updated_at = NOW() WHERE user_id = ?");
                $stmt->execute([$data['bloodSugar'], $data['uricAcid'], $bmi, $data['weight'], $data['height'], $userId]);
            } else {
                // 创建记录
                $stmt = $this->db->prepare("INSERT INTO user_health (user_id, blood_sugar, uric_acid, bmi, weight, height, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                $stmt->execute([$userId, $data['bloodSugar'], $data['uricAcid'], $bmi, $data['weight'], $data['height']]);
            }
            
            return apiSuccess(null, '健康信息更新成功');
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 生成token
     */
    private function generateToken($userId) {
        global $appConfig;
        
        $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
        $payload = json_encode([
            'user_id' => $userId,
            'iat' => time(),
            'exp' => time() + $appConfig['token_expire']
        ]);
        
        $base64Header = base64_encode($header);
        $base64Payload = base64_encode($payload);
        
        $signature = hash_hmac('sha256', $base64Header . "." . $base64Payload, $appConfig['secret_key'], true);
        $base64Signature = base64_encode($signature);
        
        return $base64Header . "." . $base64Payload . "." . $base64Signature;
    }
    
    /**
     * 从token中获取用户ID
     */
    private function getUserIdFromToken($token) {
        global $appConfig;
        
        if (!$token) {
            throw new Exception('Token不能为空');
        }
        
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            throw new Exception('Token格式错误');
        }
        
        list($base64Header, $base64Payload, $base64Signature) = $parts;
        
        // 验证签名
        $signature = base64_decode($base64Signature);
        $expectedSignature = hash_hmac('sha256', $base64Header . "." . $base64Payload, $appConfig['secret_key'], true);
        
        if (!hash_equals($signature, $expectedSignature)) {
            throw new Exception('Token签名验证失败');
        }
        
        $payload = json_decode(base64_decode($base64Payload), true);
        
        // 验证过期时间
        if ($payload['exp'] < time()) {
            throw new Exception('Token已过期');
        }
        
        return $payload['user_id'];
    }
    
    /**
     * 更新最后登录时间
     */
    private function updateLastLogin($userId) {
        $stmt = $this->db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
        $stmt->execute([$userId]);
    }
}

?>